<?php

namespace app\common\model;

use app\admin\model\jeek\shop\SkuGoods;
use tencent\api\Im;
use think\Model;
use think\Request;


class Order extends Model
{


    // 表名
    protected $name = 'order';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
//        'order_type_text',
//        'status_text'
    ];


    public function getOrderTypeList()
    {
        return ['text' => __('Order_type text'), 'audio' => __('Order_type audio'), 'video' => __('Order_type video')];
    }

    public function getStatusList()
    {
        return ['paytreat' => __('Status paytreat'), 'pending' => __('Status pending'), 'active' => __('Status active'), 'complete' => __('Status complete'), 'evaluated' => __('Status evaluated'), 'cancelled' => __('Status cancelled'), 'refund' => __('Status refund')];
    }


    public function getOrderTypeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['order_type']) ? $data['order_type'] : '');
        $list = $this->getOrderTypeList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function skuGoods()
    {
        return $this->belongsTo(SkuGoods::class, 'goods_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function user()
    {
        return $this->belongsTo(User::class, 'user_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }


    /**
     * Account:订单关闭 (自动取消)
     * User: Ixiangang
     * Date: 2025/2/8
     * Time: 15:08
     */
    public function orderClose($order_id)
    {
        if (!$order_id) return false;
        $info = self::get($order_id);
        if (!$info) return false;
        if ($info->status != 'paytreat') return false;
        $info->status = 'cancelled'; //取消订单
        $info->close_time = time();
        $info->save();
        return true;
    }


    /**
     * Account:结束订单关闭会话
     * User: Ixiangang
     * Date: 2025/2/10
     * Time: 15:10
     */
    public function orderEndChatSessions($order_id)
    {
        if (!$order_id) return false;
        $info = self::get($order_id);
        if (!$info) return false;
        if ($info->status != 'active') return false;
        # 更新订单状态
        $info->status = "complete";
        $info->remaining_minutes = 0; //剩余分钟
        $info->remaining_second = 0; //秒
        $info->meter_is = 0; //停止计时
        $info->save();
        # 关闭会话
        $ChatSessionsInfo = ChatSessions::where('id', $info->sessions_id)->find();
        if (empty($ChatSessionsInfo)) return false;
        $ChatSessionsInfo->status = "closed";
        $ChatSessionsInfo->end_time = time();
        $ChatSessionsInfo->updatetime = time();
        $ChatSessionsInfo->save();
        # 完成订单 给咨询师分钱
        SkuGoods::money($info->consultant_price, $info->goods_id, '完成订单');
        # 完成订单 给合伙人分钱
        if ($info->user_pid != 0) {
            Copartner::money($info->copartner_price, $info->user_pid, $info->id, "获取分佣");
        }
        # 更新服务次数
        SkuGoods::where('id', $info->goods_id)->setInc('sales');
        return true;
    }

    /**
     * Account:订单退款
     * User: Ixiangang
     * Date: 2025/2/13
     * Time: 10:55
     */
    public function orderRefund($order_id)
    {
        if (!$order_id) return false;
        $info = self::get($order_id);
        if (!$info) return false;
        if ($info->status == 'pending') {
            $refun = refundOrder($info->order_sn, $info->pay_type, $info->pay_price, '订单退款');
            if ($refun) {
                $info->status = 'refund';
                $info->refund_time = time();
                $info->save();
                # 删除会话
                ChatSessions::where('order_id',$order_id)->delete();

                $user_tencent_account = User::where('id', $info->user_id)->value('tencent_account');
                $goods_tencent_account = SkuGoods::where('id', $info->goods_id)->value('tencent_account');
                # 音频视频 发一个自定义消息
                if ($info->order_type == "audio") {
                    $im = new Im();
                    $com = "取消订单成功，音频订单时长：" . $info->duration_name . "；";
                    $im->from_to($user_tencent_account, $goods_tencent_account, $com);
                }

                if ($info->order_type == "video") {
                    $im = new Im();
                    $com = "取消订单成功，视频订单时长：" . $info->duration_name . "；";
                    $im->from_to($user_tencent_account, $goods_tencent_account, $com);
                }
                if ($info->order_type == "text") {
                    $im = new Im();
                    $com = "取消订单成功，图文订单时长：" . $info->duration_name . "；";
                    $im->from_to($user_tencent_account, $goods_tencent_account, $com);
                }
                return true;
            }
        }
        return true;
    }


    /**
     * Account:订单回调
     * User: Ixiangang
     * Date: 2025/2/10
     * Time: 09:44
     */
    public function notify($order_sn, $pay_price, $pay_sn = '', $paytype = '')
    {
        $order = self::get(['order_sn' => $order_sn]);
        if (!$order) return false;
        $order->status = 'pending';
        $order->pay_price = $pay_price;
        $order->pay_time = time();
        if ($pay_sn) {
            $order->pay_sn = $pay_sn;
        }
        if ($paytype) {
            $order->pay_type = $paytype;
        }
        # 更新优惠卷状态
        if ($order->coupon_log_id != 0) {
            Couponlog::where('id', $order->coupon_log_id)->update(['use_for' => '2', 'usage_time' => time()]);
        }
        # 创建会话
        $sessions_id = ChatSessions::insertGetId([
            'user_id' => $order->user_id,
            'goods_id' => $order->goods_id,
            'order_id' => $order->id,
            'message_type' => $order->order_type, //会话类型
            'start_time' => time(),
            'createtime' => time(),
        ]);
        $order->sessions_id = $sessions_id;
        $order->save();
        # 查询免费图文会话
        $freeChatSessions = ChatSessions::where(['user_id' => $order->user_id, 'goods_id' => $order->goods_id, 'message_type' => $order->order_type, 'order_id' => 0])->find();
        if (!empty($freeChatSessions)) {
            $freeChatSessions->status = 'closed';
            $freeChatSessions->end_time = time();
            $freeChatSessions->save();
        }
        $user_tencent_account = User::where('id', $order->user_id)->value('tencent_account');
        $goods_tencent_account = SkuGoods::where('id', $order->goods_id)->value('tencent_account');
        # 音频视频 发一个自定义消息
        if ($order->order_type == "audio") {
            $im = new Im();
            $com = "下单成功，音频订单时长：" . $order->duration_name . "，请预约好彼此的时间！";
            $im->from_to($user_tencent_account, $goods_tencent_account, $com);
        }

        if ($order->order_type == "video") {
            $im = new Im();
            $com = "下单成功，视频订单时长：" . $order->duration_name . "，请预约好彼此的时间！";
            $im->from_to($user_tencent_account, $goods_tencent_account, $com);
        }
        if ($order->order_type == "text") {
            $im = new Im();
            $com = "下单成功，图文订单时长：" . $order->duration_name . "，请预约好彼此的时间！";
            $im->from_to($user_tencent_account, $goods_tencent_account, $com);
        }
        return true;
    }


    /**
     * Account:计算分佣价格
     * User: Ixiangang
     * Date: 2025/2/17
     * Time: 16:04
     */
    public function getCompare($order_id)
    {
        $info = self::get($order_id);
        if (empty($info)) return false;
        # 咨询师
        $consultant_compare = config('site.consultant_compare') / 100;
        $consultant_price = bcmul($consultant_compare, $info->pay_price, 2);
        # 计算合伙人价格
        $copartner_price = 0;
        if ($info->user_pid != 0) {
//            $copartner_compare = config('site.copartner_compare') / 100;
            # 查询合伙人等级分佣
            $copartner_cata_id = Copartner::where(['user_id' => $info->user_pid])->value('copartner_cata_id');
            $copartner_compare = CopartnerCate::where(['id'=> $copartner_cata_id])->value('copartner_compare') / 100;
            $copartner_price = bcmul($copartner_compare, $info->pay_price, 2);
        }
        # 获取平台费用
        $platform_price = bcsub(bcsub($info->pay_price, $consultant_price, 2), $copartner_price, 2);
        $info->consultant_price = $consultant_price;
        $info->copartner_price = $copartner_price;
        $info->platform_price = $platform_price;
        $row = $info->save();
        if ($row) return true;
        return false;
    }


    /**
     * Account:订单信息
     * User: Ixiangang
     * Date: 2025/2/12
     * Time: 10:25
     */
    public function getOrderList($where = [])
    {
        $field = "o.id,o.status,o.goods_id,o.user_id,o.order_type,o.duration_name,o.pay_price,o.createtime,o.status,o.consultant_price
        ,g.name as goods_name,g.category_id,g.image as goods_image
        ,u.nickname,u.avatar";
        $order = "o.id desc";
        $list = self::alias('o')
            ->join('jeek_shop_sku_goods g', 'g.id = o.goods_id', 'left')
            ->join('user u', 'u.id = o.user_id', 'left')
            ->field($field)
            ->where(function ($query) use ($where) {
                # 查询用户我的订单
                if (isset($where['user_id']) && $where['user_id']) {
                    $query->where('o.user_id', '=', $where['user_id']);
                }
                # 查询咨询师我的订单
                if (isset($where['goods_id']) && $where['goods_id']) {
                    $query->where('o.goods_id', '=', $where['goods_id']);
                }
                # 状态查询
                if (isset($where['status']) && $where['status']) {
                    $where['status'] == "active" ? $query->where('o.status', 'in', 'active,pending') : $query->where('o.status', '=', $where['status']);
                }
            })
            ->order($order)
            ->select();
        array_map(function ($item) {
            # 查询咨询师分类
            $item->category_name = Category::where('id', 'in', $item->category_id)->column('name');
            return $item;
        }, $list);
        return $list;
    }

    /**
     * Account:订单详情
     * User: Ixiangang
     * Date: 2025/2/13
     * Time: 09:12
     */
    public function getOrderDetail($order_id)
    {
        $field = "o.id,o.status,o.goods_id,o.user_id,o.order_type,o.duration_name,o.pay_price,o.createtime,o.status
        ,o.remaining_minutes,o.order_sn,o.price,o.discount_price,o.coupon_price,o.close_time,o.consultant_price,o.refund_time
        ,g.name as goods_name,g.category_id,g.image as goods_image
        ,u.nickname,u.avatar";
        $order = "o.id desc";
        $info = self::alias('o')
            ->join('jeek_shop_sku_goods g', 'g.id = o.goods_id', 'left')
            ->join('user u', 'u.id = o.user_id', 'left')
            ->field($field)
            ->where(function ($query) use ($order_id) {
                $query->where('o.id', '=', $order_id);
            })
            ->order($order)
            ->find();
        if (empty($info)) return false;
        $info->remaining_minutes = $info->remaining_minutes . "分钟";
        # 咨询师类型
        $info->category_name = Category::where('id', 'in', $info->category_id)->column('name');
        # 查询评价
        if ($info->status == "evaluated") {
            $info->order_evaluate = (new OrderEvaluate())->getInfo(['order_id' => $info->id]);
        }
        return $info;
    }


}
